import React, {useState, useEffect, useRef, forwardRef, useImperativeHandle} from "react"
import BScroll from "better-scroll"
import {TDirection} from "@/common/constant";
import loading from "@/assets/loading.gif";
import './index.scss'

interface IScrollProps {
  direction: TDirection
  pullUp?: any
  pullDown?: any
  children?: any
  refresh?: boolean
  data?: any
}

const Scroll = forwardRef((props: IScrollProps, ref) => {

  console.log('-----Scroll------')

  const scrollContaninerRef: any = useRef();
  const [bScroll, setBScroll] = useState<any>();
  const [pullDownLoading, setPullDownLoading] = useState<boolean>()
  const [pullUpLoading, setPullUpLoading] = useState<boolean>()

  const {pullUp, pullDown, direction, data} = props;

  useEffect(() => {
    const scroll = new BScroll(scrollContaninerRef.current, {
      scrollX: direction === "horizental",
      scrollY: direction === "vertical",
      probeType: 3,
      click: true,
      pullUpLoad: true,
      pullDownRefresh: true
    });

    setBScroll(scroll);

    return () => {
      setBScroll(null);
    }
  }, []);

  useEffect(() => {
    if (!bScroll) return;
    console.log('bind pullingDown and pullingUp')

    bScroll.on('pullingDown', () => {
      if (pullDownLoading) return
      console.log('pullingDown')
      setPullDownLoading(true)
      pullDown(() => {
        setPullDownLoading(false)
        bScroll.finishPullDown()
        bScroll.refresh()
      })
    })

    bScroll.on('pullingUp', () => {
      console.log('pullingUp')
      setPullUpLoading(true)
      pullUp(() => {
        setPullUpLoading(false)
        bScroll.finishPullUp()
        bScroll.refresh()
      })
    })

    return () => {
      console.log('off pullingUp and  pullingDown')
      // bScroll.off('scrollEnd', bScroll);
      bScroll.off('pullingUp', bScroll);
      bScroll.off('pullingDown', bScroll);
    }
  }, [bScroll, data]);

  useImperativeHandle(ref, () => {
    if (!bScroll) return;
    return {
      refreshScroll() {
        bScroll.refresh()
      }
    }
  }, [bScroll])

  const PullDownDisplayStyle: any = pullDownLoading ? {display: ""} : {display: "none"};
  const PullUpDisplayStyle: any = pullUpLoading ? {
    display: "",
    position: "relative",
    bottom: "20px"
  } : {display: "none"};

  return (
    <div className="ScrollContainer" ref={scrollContaninerRef}>
      <div>
        <img style={PullDownDisplayStyle} alt="" src={loading}/>
        {props.children}
        <img style={PullUpDisplayStyle} alt="" src={loading}/>
      </div>
    </div>
  )
})

export default Scroll
